package ooo.reindeer.commons.utils;

import org.jasypt.util.text.BasicTextEncryptor;

public class Encrypt {

    public static final boolean supportDecryption;

    static {
        boolean temp = false;
        try {
            Class.forName("org.jasypt.util.text.BasicTextEncryptor");
            temp = true;
        } catch (ClassNotFoundException ignored) {

        }
        supportDecryption = temp;

    }

    /**
     * Encrypt
     *
     * @param text
     *         Clear text
     * @param key
     *         key
     *
     * @return Cipher text
     */
    public static String encrypt(String text, String key) {
        if (!supportDecryption){
            throw new UnsupportedOperationException("org.jasypt.util.text.BasicTextEncryptor notFound");
    }
        BasicTextEncryptor encryptor = new BasicTextEncryptor();
        encryptor.setPassword(key);
        return encryptor.encrypt(text);
    }

    /**
     * decrypt
     *
     * @param ciphertext
     *         Cipher text
     * @param key
     *         key
     *
     * @return Clear text
     */
    public static String decrypt(String ciphertext, String key) {
        if (!supportDecryption) {
            throw new UnsupportedOperationException("org.jasypt.util.text.BasicTextEncryptor notFound");
        }
            BasicTextEncryptor encryptor = new BasicTextEncryptor();
        encryptor.setPassword(key);
        return encryptor.decrypt(ciphertext);
    }

    public static void main(String[] args) {


        String name = Encrypt.encrypt("root","UCP_ENC_PASS_89SYNDF087Y73");
        System.out.println("name = " + Encrypt.decrypt(name, "UCP_ENC_PASS_89SYNDF087Y73"));

    }

}
